<template>
    <div class="form-option">
        <draggable :list="options" @end="onEnd">
            <Row v-for="(option, index) in options" class="row" :key="index" :options="{draggable:'.item'}">
                <Col span="8">
                    <Input placeholder="value" v-model="option.value" @input="handlerChange($event, index, 'value')"/>
                </Col>
                <Col span="8" offset="2">
                    <Input placeholder="label" v-model="option.label" @input="handlerChange($event, index, 'label')"/>
                </Col>
                <Col span="4" offset="2">
                    <div @click="handlerRemove(index)" v-if="index!==(options.length-1)">
                        <Icon type="ios-close-circle"/>删除
                    </div>
                </Col>
                <Col span="4" offset="2">
                    <div v-if="index===(options.length-1)" @click="handlerAdd">
                        <Icon type="ios-add-circle" />添加
                    </div>
                </Col>
                
                
            </Row>
        </draggable>
        
    </div>
</template>
<script>
import { Vue, Component, Model, Watch } from "vue-property-decorator"
import Draggable from 'vuedraggable'
@Component({
    components: {
        Draggable
    }
})
export default class extends Vue {
    @Model('change', { type: Array }) value:any

    options = [];
    @Watch('value')
    onValueChange() {
        this.options = [];
        for (let i = 0; i < this.value.length; i++) {
            this.options.push({
                value: this.value[i].value,
                label: this.value[i].label
            })
        }
    }
    
    handlerChange(value, index, key) {
        // if (key === 'value') { // value不允许重复
        //     this.options.forEach((o, i) => {
        //         if (i !== index && o.value === value) {
        //             return;
        //         }
        //     })
        // }
        this.options[index][key] = value;
        this.$emit('change', [...this.options]);
    }

    handlerRemove(index) {
        this.options.splice(index, 1);
        this.$emit('change', [...this.options]);
    }

    handlerAdd() {
        this.options.unshift({name: '', value: ''});
        this.$emit('change', [...this.options]);
    }

    onEnd() {
        this.$emit('change', [...this.options]);
    }

    mounted () {
        this.onValueChange();
    }
   
}
</script>
<style lang="less" scoped>
    .row {
        margin-bottom: 10px;
    }
</style>
